package com.shoujifeng.snowmusic.player;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.preference.PreferenceManager;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.Gallery;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.shoujifeng.snowmusic.ListView.XListView;
import com.shoujifeng.snowmusic.ListView.XListView.IXListViewListener;
import com.shoujifeng.snowmusic.ListView.XListViewFooter;
import com.shoujifeng.snowmusic.adapter.GalleryAdapter;
import com.shoujifeng.snowmusic.adapter.OnlineListAdapter;
import com.shoujifeng.snowmusic.db.DatabaseUtil;
import com.shoujifeng.snowmusic.player.http.GlobalValue;
import com.shoujifeng.snowmusic.player.http.ServerAccess;
import com.shoujifeng.snowmusic.player.interfaces.MoreInterface;
import com.shoujifeng.snowmusic.player.utils.LoadMask;
import com.shoujifeng.snowmusic.player.utils.MusicPlayer;
import com.shoujifeng.snowmusic.player.utils.TabHostAnim;

/**
 * 在线热歌
 * 
 * @author Administrator
 * 
 */
public class OnlineHotActivity extends Activity implements SensorEventListener,IXListViewListener{
	private XListView listView;
	private OnlineListAdapter mAdapter;
	private Gallery mGallery;
	private GalleryAdapter mGalleryAdapter;
	private final int UPDATE_DATA = 0;
	private final int UPDATE_ONE = 1;
	private ServerAccess serverAccess;
	private ArrayList<HashMap<String, Object>> mTmpList;
	private ArrayList<HashMap<String, Object>> mMusicList;
	private ArrayList<HashMap<String, Object>> mAdList;
	private Thread accThread;
	private View imageView;
	private Handler mHandler;
	private int mPage = 0;
	private LoadMask mLoadMask;
	private LinearLayout linearLayout1;
	private LinearLayout linearLayout;


	// 翻页控件
	private ViewPager mViewPager;
	// 3个是底部显示当前状态点imageView
	private ImageView mPage0;
	private ImageView mPage1;
	private ImageView mPage2;
	
	//收藏
	private boolean bHave;
	private int index;
	
	//数据库操作
	DatabaseUtil mDb;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		super.onCreate(savedInstanceState);
		setContentView(R.layout.online_hot_lay);
		init();
		setListView();
		initGlobalValue();
		mLoadMask = new LoadMask(this);
		mLoadMask.startLoad();
		accThread = new Thread(runnable);
		accThread.start();
		
		mDb = new DatabaseUtil(this);
		XListViewFooter.mContentView.setVisibility(View.GONE);
	}

	private void init() {
		mHandler = new Handler();
		
		serverAccess = new ServerAccess(OnlineHotActivity.this);
		listView = (XListView) findViewById(R.id.online_hot_listView);
		listView.setPullLoadEnable(true);
		listView.setXListViewListener(this);
		
		imageView = LayoutInflater.from(OnlineHotActivity.this).inflate(
				R.layout.image_view, null);
		listView.addHeaderView(imageView);
		
		listView.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				// TODO Auto-generated method stub
				Intent intent = new Intent(OnlineHotActivity.this, MusicPlayerActivity.class);
				MusicPlayerActivity.mOlineMusicList = mMusicList;
				MusicPlayer.position = arg2-1;
				MusicPlayerActivity.isOnline = true ;
				 MusicPlayer.MUSCI_MSG =1;
				startActivity(intent);
				
				TabHostAnim.set(R.anim.bottom_in, android.R.anim.fade_out);
			}
		});
	}
	
	private void creatImg(){
		linearLayout1 = (LinearLayout) imageView.findViewById(R.id.linearLayout1);
		for(int i = 0;i<mAdList.size();i++){
			linearLayout = new LinearLayout(OnlineHotActivity.this);
			ImageView image = new ImageView(OnlineHotActivity.this);
			linearLayout.setPadding(5, 5, 5, 5);	
			if(i==0){
				image.setBackgroundResource(R.drawable.no);
			}
			else{
				image.setBackgroundResource(R.drawable.on);
			}
			linearLayout.addView(image);
			
			linearLayout1.addView(linearLayout);
		}
	}
	// 设定画廊的显示方式和内容
		public void prepare() {
			
			mGallery = (Gallery) imageView.findViewById(R.id.home_gallery);
			mGalleryAdapter = new GalleryAdapter(this,mAdList);
			mGallery.setAdapter(mGalleryAdapter);
			mGallery.setOnItemClickListener(new OnItemClickListener() {

				@Override
				public void onItemClick(AdapterView<?> parent, View view,
						int position, long id) {
					Intent intent = new Intent(OnlineHotActivity.this,OnlineAdvContentActivity.class);
					intent.putExtra(ServerAccess.ID, mAdList.get(position).get(ServerAccess.ID).toString());
					startActivity(intent);
					
					TabHostAnim.set(R.anim.right_in, R.anim.no_move);
				}

			});
			mGallery.setOnItemSelectedListener(new OnItemSelectedListener() {

				@Override
				public void onItemSelected(AdapterView<?> arg0, View arg1,
						int arg2, long arg3) {
					//mMyView.setSeletion(arg2);
					linearLayout.removeAllViews();
					linearLayout1.removeAllViews();
						for(int i = 0;i<mAdList.size();i++){
							linearLayout = new LinearLayout(OnlineHotActivity.this);
							ImageView image = new ImageView(OnlineHotActivity.this);
							linearLayout.setPadding(5, 5, 5, 5);	
							if(i==arg2){
								image.setBackgroundResource(R.drawable.no);
							}
							else{
								image.setBackgroundResource(R.drawable.on);
							}
							linearLayout.addView(image);
							
							linearLayout1.addView(linearLayout);
						}
					
				}

				@Override
				public void onNothingSelected(AdapterView<?> arg0) {

				}
			});
		}

	private void setListView() {
		mMusicList = new ArrayList<HashMap<String, Object>>();
		String keys[] = new String[] { ServerAccess.MUSIC_NAME,
				ServerAccess.SINGER, ServerAccess.VIEWS };
		mAdapter = new OnlineListAdapter(this, mMusicList, new int[] {
				R.id.special_name, R.id.playerName, R.id.countTxt }, keys,
				new String[] { ServerAccess.ICON_URL },
				new int[] { R.id.face }, R.drawable.icon_music_default,
				R.layout.online_hot_list);
		mAdapter.addInterfaceOnMore(mMoreInterface);
		listView.setAdapter(mAdapter);
	}
	
	//添加List回调事件
	private MoreInterface mMoreInterface = new MoreInterface() {
		
		
		@Override
		public void OnClickDownload(final int position) {
			HashMap<String, Object> map = mMusicList.get(position);
			
			
			GlobalValue.g_DownloadManager.addDownload(map);
			
			Toast.makeText(OnlineHotActivity.this, "已加入下载!", Toast.LENGTH_LONG).show();
		}

		@Override
		public void OnClickConllect(int position, Boolean have) {
			if(ServerAccess.uid > 0) {
				
				HashMap<String, Object> map = mMusicList.get(position);
				int index = Integer.parseInt(map.get(ServerAccess.INDEX).toString());
				
				OnlineHotActivity.this.index = index;
				
				bHave = have;
				if(!have) {
					//写入本地
					mDb.insertConllect(index, ServerAccess.uid);
					
					//写入网络
					Thread thread = new Thread(delRunnable);
					thread.start();
					
					//收藏成功
					Toast.makeText(OnlineHotActivity.this, "收藏成功!", Toast.LENGTH_LONG).show();
				}
				else {
					mDb.deleteConllect(index);
					
					//写入网络
					Thread thread = new Thread(delRunnable);
					thread.start();
					
					Toast.makeText(OnlineHotActivity.this, "已删除收藏!", Toast.LENGTH_LONG).show();
				}
				
				
			}
			else {
				//跳登陆
				Intent intent = new Intent(OnlineHotActivity.this,
						LoginActivity.class);
				startActivity(intent);
				
				overridePendingTransition(R.anim.right_in, R.anim.left_out);
			}
		}
	};

	
	private void initGlobalValue() {
		GlobalValue.initSDAddr();

		GlobalValue.addUrl(ServerAccess.HOT_MUSIC_LIST,
				"http://www.snowmusic.com.cn/mobile_api/hot_music_list.php");
		GlobalValue.addUrl(ServerAccess.ADV_LIST,
				"http://www.snowmusic.com.cn/mobile_api/adv_list.php");
	}

	protected Handler handler = new Handler() {
		@SuppressWarnings("unchecked")
		@Override
		public void handleMessage(Message msg) {

			switch (msg.what) {
			case UPDATE_DATA: {
				mLoadMask.stopLoad();
				System.out.println(mTmpList.size()+"-------------------");
					
				XListViewFooter.mContentView.setVisibility(View.VISIBLE);
				
				updateArrayList();
			}
				break;
			case UPDATE_ONE:{
				creatImg();
				prepare();
			}
				break;
			default:
				break;
			}
			super.handleMessage(msg);
		}
	};

	//删除收藏
	//BY Kress
	protected Runnable delRunnable = new Runnable() {
		
		@Override
		public void run() {
			try {
				if(bHave) {
					serverAccess.delToConllect(index, ServerAccess.uid, new String[]{});
				}
				else {
					serverAccess.addToConllect(index, ServerAccess.uid, new String[]{});
				}
			} catch (Exception e) {
				// TODO: handle exception
			}
		}
	};
	// 创建多线程获取数据
	protected Runnable runnable = new Runnable() {

		@Override
		public void run() {
			// TODO Auto-generated method stub
			try {
				
					String[] keys = new String[] { ServerAccess.MUSIC_NAME,
							ServerAccess.SINGER, ServerAccess.VIEWS,ServerAccess.ICON_URL,
							ServerAccess.INDEX, ServerAccess.CODE ,ServerAccess.LAN,ServerAccess.MUSIC_FILE,ServerAccess.ALBUM};
					mTmpList = new ArrayList<HashMap<String, Object>>();
					mTmpList = serverAccess.getHotMusicListOfIndex(keys,mPage);
					sendMessage(UPDATE_DATA);
				
					mAdList = new ArrayList<HashMap<String,Object>>();
					String keys2[] = new String[] {ServerAccess.ID,ServerAccess.MID,ServerAccess.STATE,ServerAccess.ICON_URL,ServerAccess.CODE};
					mAdList = serverAccess.getListAdv("2",keys2);
					sendMessage(UPDATE_ONE);
					
					

			} catch (Exception e) {
				// TODO: handle exception
				e.printStackTrace();
			}
		}
	};

	// 发送消息到Handler
	private void sendMessage(int what) {
		Message msg = new Message();
		msg.what = what;
		handler.sendMessage(msg);
	}

	// 若在线程中更新与Adapter的动态数组将会产生致命错误。
	private void updateArrayList() {

		if (mMusicList != null) {
			int count = mTmpList.size();
			for (int i = 0; i < count; i++) {
				mMusicList.add(mTmpList.get(i));
			}

			 mTmpList.clear();
			 mTmpList = null;
		}

		mAdapter.notifyDataSetChanged();
	}

	@Override
	public void onAccuracyChanged(Sensor arg0, int arg1) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onSensorChanged(SensorEvent arg0) {
		// TODO Auto-generated method stub

	}

	

	private void onLoad() {
		listView.stopRefresh();
		listView.stopLoadMore();
		listView.setRefreshTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
	}

	@Override
	public void onLoadMore() {
		// TODO Auto-generated method stub

		mHandler.postDelayed(new Runnable() {
			@Override
			public void run() {
				mPage = mPage+1;
				accThread = new Thread(runnable);
				accThread.start();
				onLoad();
			}
		}, 1000);
		
	}

}
